package club.hicode.daydayup.rpc.demo.client.frame;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * 客户端启动
 * @author Liu Chunfu
 * @date 2018-08-31 上午10:23
 **/
public class ClientStart {

	static {
		try {
			start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Channel CHANNEL;

	private static void start() throws Exception {
		EventLoopGroup group = new NioEventLoopGroup();
		Bootstrap bootstrap = new Bootstrap();

		Channel channel = bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
				.option(ChannelOption.SO_KEEPALIVE, true).handler(new ChannelInitializer<NioSocketChannel>() {
					@Override
					protected void initChannel(NioSocketChannel ch) throws Exception {
						ChannelPipeline pipeline = ch.pipeline();
						pipeline.addLast("framer",
								new DelimiterBasedFrameDecoder(8192, Unpooled.copiedBuffer("$".getBytes())));
						pipeline.addLast("decoder", new StringDecoder());
						pipeline.addLast("encoder", new StringEncoder());
					}
				}).connect("localhost", 29201).sync().channel();
		CHANNEL = channel;
	}
}
